<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<view class="cu-custom" :style="[{height:StatusBar + 'px'}]">
			<view class="cu-bar fixed" :style="[{paddingTop: StatusBar + 'px',height: CustomBar+'px'}]">
				<navigator v-if="CanBack" open-type="navigateBack" class="bg-black-black round margin-lr "
					style="padding: 5px 6px;"><text class="cuIcon-back "></text></navigator>
				<navigator v-else open-type="switchTab" url="/pages/home/index" class="bg-black-black round margin-lr "
					style="padding: 5px 6px;"><text class="cuIcon-home">首页</text></navigator>
			</view>
		</view>
		<image class="cu-avatar seckill-image" :src="seckillInfo.picUrl"></image>
		<view class="cu-card article no-card padding-lr-sm margin-top-xs" v-if="seckillInfo.goodsSku">
			<view class="padding-sm radius seckill-bgimage">
				<view class="flex justify-between align-center">
					<view class="text-lg text-white text-bold overflow-1 margin-right">{{seckillInfo.name}}</view>
					<view @click="shareShowFun" class="cuIcon-forward text-sm text-white flex align-center"></view>
				</view>
				<view class="flex align-center justify-between margin-top-xs">
					<view class="flex align-center">
						<view class="text-price text-bold text-xxl text-white margin-right-sm">
							{{seckillInfo.seckillPrice}}</view>
						<view class="text-price text-decorat text-white">{{seckillInfo.goodsSku.salesPrice}}</view>
					</view>
					<view class="cu-item flex text-white" v-if="seckillInfo.seckillHall&&outTime>0">
						<view class="text-sm">距本场结束：</view>
						<count-down :textColor="'#ffffff'" :outTime="outTime" @countDownDone="countDownDone">
						</count-down>
					</view>
					<view class="cu-item" v-else-if="seckillInfo.seckillHall">
						<view class="text-white padding-lr-sm">{{seckillInfo.seckillHall.hallTime}}点开抢</view>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-item padding-lr-sm margin-top-xs" v-if="seckillInfo.goodsSku">
			<view class="content bg-white radius padding-sm">
				<view class="desc">
					<view class="text-black text-lg text-bold">{{seckillInfo.goodsSpu.name}}</view>
					<view class="text-gray text-df margin-top-xs"
						v-if="seckillInfo.goodsSku&&seckillInfo.goodsSku.specs&&seckillInfo.goodsSku.specs.length > 0">
						{{specInfo}}</view>
					<view class="flex justify-between margin-top-sm">
						<text class="text-df text-gray">已售{{seckillInfo.seckillNum}}</text>
						<text class="text-df text-gray">限量{{seckillInfo.limitNum}}</text>
						<text class="text-blue text-df" @tap="ruleShow">秒杀规则</text>
					</view>
					<view class="cu-tag bg-red radius sm margin-left"
						v-if="seckillInfo.goodsSpu.freightTemplat.type == '2'">包邮</view>
				</view>
			</view>
		</view>
		<view v-if="theme.showType!='2'" class="padding-lr-sm margin-top-xs">
			<view class="bg-white radius padding-top-sm">
				<navigator class="padding-lr-sm padding-bottom-sm" hover-class="none"
					:url="'/pages/shop/shop-detail/index?id=' + seckillInfo.shopInfo.id">
					<text class="text-black text-df"><text
							class="cuIcon-shop margin-right-xs"></text>{{seckillInfo.shopInfo.name}}</text>
					<view class="margin-top-xs flex align-center">
						<view class="cu-avatar lg radius"
							:style="'background-image:url(' + seckillInfo.shopInfo.imgUrl + ')'"></view>
						<view class="margin-left-sm">
							<text class="text-sm text-gray overflow-1">{{seckillInfo.shopInfo.address}}</text>
							<text class="text-sm text-gray">{{seckillInfo.shopInfo.phone}}</text>
						</view>
					</view>
				</navigator>
			</view>
		</view>
		<view class="cu-card no-card padding-lr-sm margin-top-xs" style="padding-bottom: 120rpx;">
			<view class="cu-item" style="border-radius: 12rpx 12rpx 0 0;">
				<view class="cu-bar bg-white">
					<view class="content">商品信息</view>
				</view>
				<view class="bg-white">
					<jyf-parser :html="article_description"></jyf-parser>
				</view>
				<view class="cu-load bg-gray to-down">已经到底啦...</view>
			</view>
		</view>
		<view class="cu-bar bg-white tabbar border shop foot">
			<navigator v-if="theme.showType!='2'" class="action bg-white" hover-class="none"
				:url="'/pages/shop/shop-detail/index?id=' + seckillInfo.shopInfo.id">
				<view class="cuIcon-shop text-red " style="font-size: 20px;"></view>
				<text class="text-red">店铺</text>
			</navigator>
			<navigator class="action bg-white" open-type="navigate"
				:url="'/pages/customer-service/customer-service-list/index?shopId='+seckillInfo.shopId">
				<view class="cuIcon-comment"></view>客服
			</navigator>
			<navigator class="action" open-type="switchTab" url="/pages/shopping-cart/index">
				<view class="cuIcon-cart" style="font-size: 20px;">
					<view class="cu-tag badge">{{shoppingCartCount}}</view>
				</view>购物车
			</navigator>
			<view class="margin-right-sm" @tap="tobuy">
				<view class="bg-orange round shadow-blur text-center" style="width: 200rpx;">
					<view class="text-xs">原价购买</view>
					<view class="text-price text-lg text-bold">{{seckillInfo.goodsSku.salesPrice}}</view>

				</view>
			</view>
			<view @tap="toSeckillBuy">
				<view class="round  margin-right-sm shadow-blur text-center"
					:class="'bg-' + (outTime>0  ? 'red' : 'gray')" style="width: 200rpx;">
					<view v-if="outTimeOk>0" class="text-xs ">
						<view>即将开始</view>
						<view style="min-height: 38rpx;">
							<count-down :textColor="'#999999'" :outTime="outTimeOk" @countDownDone="countDownDone"></count-down>
						</view>
					</view>
					<view v-else>
						<view class="text-xs">
							{{outTime>0 ? '秒杀价' : '已结束'}}
						</view>
						<view class="text-price text-lg text-bold">{{seckillInfo.seckillPrice}}</view>
					</view>
				</view>
			</view>
		</view>
		<view :class="'cu-modal ' + modalRule">
			<view class="cu-dialog bg-white">
				<view class="cu-bar  justify-end">
					<view class="content">规则说明</view>
					<view class="action" @tap="ruleHide">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl text-left">
					<text>{{seckillInfo.seckillRule}}</text>
				</view>
			</view>
		</view>
		<view :class="'cu-modal ' + (seckillInfo.goodsSpu.shelf=='0'||!seckillInfo.goodsSku ? 'show' : '')">
			<view class="cu-dialog bg-white">
				<view class="cu-bar  justify-end">
					<view class="content">提示</view>
				</view>
				<view class="padding-xl">
					抱歉，该商品已下架
				</view>
				<view class="padding">
					<navigator open-type="navigateBack" class="cu-btn margin-top response lg"
						:class="'bg-'+theme.themeColor">
						确定
					</navigator>
				</view>
			</view>
		</view>
		<!-- 分享组件 -->
		<share-component v-model="showShare" :shareParams="shareParams"></share-component>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	import shopInfo from "components/shop-info/index";
	const util = require("@/utils/util.js");
	const {
		base64src
	} = require("utils/base64src.js");
	const app = getApp();
	import api from '@/utils/api'
	import numberUtil from 'utils/numberUtil.js'
	import dateUtil from 'utils/dateUtil.js'
	import jweixin from 'utils/jweixin'

	import countDown from "@/components/count-down/index";
	import shareComponent from "@/components/share-component/index"

	export default {

		computed: {},
		data() {
			return {
				CanBack: true,
				CustomBar: this.CustomBar,
				StatusBar: this.StatusBar,
				theme: app.globalData.theme, //全局颜色变量
				dateUtil: dateUtil,
				numberUtil: numberUtil,
				seckillInfo: {
					shopInfo: {},
					name: '',
					seckillNum: 0,
					hallTime: 0,
					goodsSpu: {
						freightTemplat: {}
					},
					goodsSku: {
						specs: []
					},
				},
				disabled: false,
				parameter: {},
				shareShow: '',
				curLocalUrl: '',
				userInfo: null,
				modalRule: '',
				seckillHallInfoId: "",
				specInfo: "",
				cutPercent: "",
				canCutPrice: "",
				havCutPrice: "",
				posterUrl: "",
				posterShow: false,
				posterConfig: "",
				article_description: "",
				hasBargainUser: false, //是否存在砍价数据
				bargainUserId: '',
				curHour: 0,
				outTime: -1,
				outTimeOk: -1, //开始抢购
				showShare: false,
				shareParams: {},
				shoppingCartCount: 0,
			};
		},

		components: {
			shareComponent,
			countDown,
		},
		// 组件所在页面的生命周期函数
		mounted: function() {
			let pages = getCurrentPages()
			if (pages.length <= 1 || pages[pages.length - 1].route == 'pages/login/index') { //判断是否能返回
				this.CanBack = false
			} else {
				this.CanBack = true
			}
		},
		props: {},
		onShow() {
			this.curHour = this.$moment().format("H");//当前小时
			this.seckillInfoGet();
			this.shoppingCartCountFun();
		},
		onHide() {
			this.outTimeOk = 0
		},
		onLoad(options) {
			// 保存别人分享来的 userCode
			util.saveSharerUserCode(options);
			this.dateUtil = dateUtil;
			this.numberUtil = numberUtil;
			let seckillHallInfoId;
			if (options.scene) {
				//接受二维码中参数
				let scenes = decodeURIComponent(options.scene).split('&');
				seckillHallInfoId = scenes[0];
			} else {
				if (options.seckillHallInfoId) {
					seckillHallInfoId = options.seckillHallInfoId;
				} else if (options.id) {
					seckillHallInfoId = options.id;
				}
			}
			this.seckillHallInfoId = seckillHallInfoId;
			app.initPage().then(res => {
				this.userInfo = uni.getStorageSync('user_info');
			});

		},
		onShareAppMessage: function() {
			let seckillInfo = this.seckillInfo;
			let title = seckillInfo.shareTitle;
			let imageUrl = seckillInfo.picUrl;
			let path = 'pages/seckill/seckill-detail/index?seckillHallInfoId=' + this.seckillHallInfoId;

			const userInfo = uni.getStorageSync('user_info')
			const userCode = userInfo ? '&sharer_user_code=' + userInfo.userCode : ''
			path = path + userCode;
			return {
				title: title,
				path: path,
				imageUrl: imageUrl,
				success: function(res) {
					if (res.errMsg == 'shareAppMessage:ok') {
						console.log(res.errMsg);
					}
				},
				fail: function(res) { // 转发失败
				}
			};
		},
		methods: {
			shoppingCartCountFun() {
				api.shoppingCartCount().then(res => {
					this.shoppingCartCount = res.data; //设置TabBar购物车数量
					app.globalData.shoppingCartCount = this.shoppingCartCount + '';
				});
			},
			//查询秒杀详情
			seckillInfoGet() {
				api.seckillInfoGet(this.seckillHallInfoId).then(res => {
					res.data.goodsSpu.freightTemplat = res.data.goodsSpu.freightTemplat ? res.data.goodsSpu
						.freightTemplat : {}
					if (res.data.seckillHall) {
						let hallHour = Number(res.data.seckillHall.hallTime);//秒杀时间
						let curDate = this.$moment().format("YYYY-MM-DD");
						// 必须当前日期和当前时间相同才能进行秒杀
						if (curDate == res.data.seckillHall.hallDate) {
							this.curHour = this.$moment().format("H");//当前小时
							// 计算倒计时时间
							const curDateTime = new Date().getTime(); //当前时间
							this.outTimeOk = -1
							this.outTime = -1
							if (hallHour == this.curHour) {//当前秒杀时间点
								let nextHour = hallHour + 1;
								let nextDateTime = res.data.seckillHall.hallDate + ' ' + nextHour + ':00:00';
								let timeTemp = this.$moment(nextDateTime).toDate();
								this.outTime = new Date(timeTemp).getTime() - curDateTime; //下一个整点时间
							} else if (hallHour > this.curHour) {
								let seckillDateTime = res.data.seckillHall.hallDate + ' ' + hallHour + ':00:00';
								let seckillTimeTemp = this.$moment(seckillDateTime).toDate();
								this.outTimeOk = new Date(seckillTimeTemp).getTime() - curDateTime; //下一个整点时间
							}
						}
					}
					let specInfo = '';
					if (res.data.goodsSku && res.data.goodsSku.specs)
						res.data.goodsSku.specs.forEach(function(specItem, index) {
							specInfo = specInfo + specItem.specValueName;
							if (res.data.goodsSku.specs.length != index + 1) {
								specInfo = specInfo + ';';
							}
						});
					this.specInfo = specInfo;
					this.seckillInfo = res.data;
					setTimeout(() => {
						this.article_description = this.seckillInfo.goodsSpu ? this.seckillInfo.goodsSpu
							.description : '';
					}, 300);
					// #ifdef H5
					this.curLocalUrl = util.setH5ShareUrl();
					// #endif
				});
			},
			//立即秒杀
			toSeckillBuy(e) {
				let seckillInfo = this.seckillInfo;
				if (this.outTime < 1) {
					uni.showToast({
						title: '当前时间不能发起秒杀！',
						icon: 'none'
					})
					return;
				}
				let goodsSpu = seckillInfo.goodsSpu;
				let goodsSku = seckillInfo.goodsSku;
				if (goodsSku.stock > 0) {
					/* 把参数信息异步存储到缓存当中 */
					uni.setStorage({
						key: 'param-orderConfirm',
						data: [{
							spuId: goodsSpu.id,
							skuId: goodsSku.id,
							quantity: 1,
							salesPrice: seckillInfo.seckillPrice,
							spuName: goodsSpu.name,
							specInfo: this.specInfo,
							picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
							freightTemplat: goodsSpu.freightTemplat,
							weight: goodsSku.weight,
							volume: goodsSku.volume,
							orderType: '3',
							marketId: seckillInfo.id,
							relationId: seckillInfo.seckillHall.id,
							shopInfo: seckillInfo.shopInfo
						}]
					});
					uni.navigateTo({
						url: '/pages/seckill/seckill-order-confirm/index'
					});
				} else {
					uni.showToast({
						title: '秒杀商品库存不足',
						icon: 'none',
						duration: 2000
					});
				}
			},
			//原价购买
			tobuy() {
				let seckillInfo = this.seckillInfo;
				let goodsSpu = seckillInfo.goodsSpu;
				let goodsSku = seckillInfo.goodsSku;
				let specInfo = this.specInfo;
				/* 把参数信息异步存储到缓存当中 */

				uni.setStorage({
					key: 'param-orderConfirm',
					data: [{
						spuId: goodsSpu.id,
						skuId: goodsSku.id,
						quantity: 1,
						salesPrice: goodsSku.salesPrice,
						spuName: goodsSpu.name,
						specInfo: specInfo,
						picUrl: goodsSku.picUrl ? goodsSku.picUrl : goodsSpu.picUrls[0],
						pointsDeductSwitch: goodsSpu.pointsDeductSwitch,
						pointsDeductScale: goodsSpu.pointsDeductScale,
						pointsDeductAmount: goodsSpu.pointsDeductAmount,
						pointsGiveSwitch: goodsSpu.pointsGiveSwitch,
						pointsGiveNum: goodsSpu.pointsGiveNum,
						freightTemplat: goodsSpu.freightTemplat,
						weight: goodsSku.weight,
						volume: goodsSku.volume,
						shopInfo: seckillInfo.shopInfo
					}]
				});
				uni.navigateTo({
					url: '/pages/order/order-confirm/index'
				});
			},
			shareShowFun() {
				// #ifdef H5
				this.curLocalUrl = util.setH5ShareUrl();
				// #endif
				// #ifdef APP-PLUS
				this.curLocalUrl = util.setAppPlusShareUrl();
				// #endif
				let desc = '长按识别小程序码';
				let shareImg = this.seckillInfo.picUrl;
				// #ifdef H5 || APP-PLUS
				desc = '长按识别二维码';
				// h5的海报分享的图片有的有跨域问题，所以统一转成base64的
				// 之所以不在组件里面转换是因为无法区分哪张image图片需要处理，一般处理主图
				shareImg = util.imgUrlToBase64(shareImg);
				// #endif
				//海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
				let posterConfig = {
					width: 750,
					height: 1280,
					backgroundColor: '#fff',
					debug: false,
					blocks: [{
						width: 690,
						height: 808,
						x: 30,
						y: 183,
						borderWidth: 2,
						borderColor: '#f0c2a0',
						borderRadius: 20
					}, {
						width: 634,
						height: 74,
						x: 59,
						y: 770,
						backgroundColor: '#fff',
						opacity: 0.5,
						zIndex: 100
					}],
					texts: [{
						x: 30,
						y: 113,
						baseLine: 'top',
						text: this.seckillInfo.shareTitle,
						fontSize: 38,
						color: '#080808'
					}, {
						x: 92,
						y: 810,
						fontSize: 38,
						baseLine: 'middle',
						text: this.seckillInfo.goodsSpu.name,
						width: 570,
						lineNum: 1,
						color: '#080808',
						zIndex: 200
					}, {
						x: 59,
						y: 895,
						baseLine: 'middle',
						text: [{
							text: '秒杀价',
							fontSize: 28,
							color: '#ec1731'
						}, {
							text: '¥' + this.seckillInfo.seckillPrice,
							fontSize: 36,
							color: '#ec1731',
							marginLeft: 30
						}]
					}, {
						x: 522,
						y: 895,
						baseLine: 'middle',
						text: '原价 ¥' + this.seckillInfo.goodsSku.salesPrice,
						fontSize: 28,
						color: '#929292'
					}, {
						x: 59,
						y: 945,
						baseLine: 'middle',
						text: [{
							text: this.seckillInfo.goodsSpu.sellPoint,
							fontSize: 28,
							color: '#929292',
							width: 570,
							lineNum: 1
						}]
					}, {
						x: 360,
						y: 1065,
						baseLine: 'top',
						text: desc,
						fontSize: 38,
						color: '#080808'
					}, {
						x: 360,
						y: 1123,
						baseLine: 'top',
						text: '限时秒杀，抢到就是赚到！',
						fontSize: 28,
						color: '#929292'
					}],
					images: [{
						width: 634,
						height: 634,
						x: 59,
						y: 210,
						url: shareImg
					}, {
						width: 230,
						height: 230,
						x: 92,
						y: 1020,
						url: null,
						qrCodeName: 'qrCodeName', // 二维码唯一区分标识
					}]
				};
				let userInfo = uni.getStorageSync('user_info');

				if (userInfo && userInfo.headimgUrl) {
					//如果有头像则显示
					posterConfig.images.push({
						width: 62,
						height: 62,
						x: 30,
						y: 30,
						borderRadius: 62,
						url: userInfo.headimgUrl
					});
					posterConfig.texts.push({
						x: 113,
						y: 61,
						baseLine: 'middle',
						text: userInfo.nickName,
						fontSize: 32,
						color: '#8d8d8d'
					});
				}


				// let path = 'pages/seckill/seckill-detail/index?seckillHallInfoId=' + this.seckillHallInfoId;
				// this.curLocalUrl = '&seckillHallInfoId=' + this.seckillHallInfoId;
				this.shareParams = {
					title: this.seckillInfo.shareTitle,
					desc: this.seckillInfo.goodsSpu.name,
					imgUrl: this.seckillInfo.picUrl,
					url: this.curLocalUrl,
					scene: this.seckillHallInfoId,
					page: 'pages/seckill/seckill-detail/index',
					posterConfig: posterConfig
				}
				this.showShare = true;
			},
			ruleShow() {
				this.modalRule = 'show';
			},
			ruleHide() {
				this.modalRule = '';
			},
			countDownDone() {
				this.seckillInfoGet();
			}
		}
	};
</script>
<style>
	.bg-black-black {
		background-color: rgba(0, 0, 0, 0.5);
		color: #ffffff;
	}

	.seckill-image {
		background-color: #fff;
		width: 100%;
		height: calc(100vw);
	}

	.seckill-bgimage {
		background-image: url(../../../static/public/img/seckill-bgimage.png);
		background-repeat: no-repeat;
		background-size: 100% 180rpx;
	}

	.show-bg {
		height: 84%;
		margin-top: 120rpx;
	}

	.image-box {
		height: 90%;
	}

	.show-btn {
		margin-top: -130rpx;
	}
</style>
